package service

import (
	"context"
	"gitee.com/WisdomClassroom/core"

	"gitee.com/WisdomClassroom/Course/glb"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"gorm.io/gorm"
)

func (s *Service) GetCourse(ctx context.Context, request *pb.GetCourseRequest) (*pb.GetCourseResponse, error) {
	course := &models.Course{UUID: request.GetUUID()}
	err := glb.DB.Preload("Chapters").Take(course).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return &pb.GetCourseResponse{Status: &pb.ResponseStatus{
				Code:    core.ResponseStatusCodeOtherError,
				Message: "课程不存在",
			}}, nil
		}
		glb.Logger.Error(err.Error())
		return getCourseRespSvrErr, nil
	}

	chapters := make([]*pb.ChapterBasicInfo, 0, len(course.Chapters))
	for _, chapter := range course.Chapters {
		chapters = append(chapters, &pb.ChapterBasicInfo{
			UUID:        chapter.UUID,
			Name:        chapter.Name.String,
			Description: chapter.Description.String,
			Index:       chapter.Index.Int32,
		})
	}

	return &pb.GetCourseResponse{
		Status:      &pb.ResponseStatus{Code: core.ResponseStatusCodeSuccess},
		Name:        course.Name.String,
		Description: course.Description.String,
		Chapters:    chapters,
	}, nil
}
